package com.bitdf.txing.seckill.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.seckill.service.SeckillService;
import com.bitdf.txing.seckill.to.SeckillSkuRedisTo;
import com.bitdf.txing.seckill.to.SeckillTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Description:
 * @createTime: 2020-07-10 11:01
 **/
@Controller
@Slf4j
@RequestMapping("${txing.request.path.seckill}")
public class SeckillController {


    @Autowired
    private SeckillService seckillService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 当前时间可以参与秒杀的商品信息
     * @return
     */
    @GetMapping(value = "/skus/current/get")
    @ResponseBody
    public R getCurrentSeckillSkus() {

        //获取到当前可以参加秒杀商品的信息
        List<SeckillSkuRedisTo> vos = seckillService.getCurrentSeckillSkus();

        return R.ok().setData(vos);
    }


    /**
     * 根据skuId查询商品是否参加秒杀活动
     * @param skuId
     * @return
     */
    @GetMapping(value = "/sku/seckill/{skuId}")
    @ResponseBody
    public R getSkuSeckilInfo(@PathVariable("skuId") Long skuId) {

        SeckillSkuRedisTo to = seckillService.getSkuSeckilInfo(skuId);

        return R.ok().setData(to);
    }


    /**
     * 商品进行秒杀(秒杀开始) 第一种方案（没引入队列）
     * @param killId
     * @param key
     * @param num
     * @return
     */
//    @GetMapping(value = "/kill")
//    public String seckill(@RequestParam("killId") String killId,
//                          @RequestParam("key") String key,
//                          @RequestParam("num") Integer num,
//                          Model model) {
//
//        long s1 = System.currentTimeMillis();
//
//
//        String orderSn = null;
//        try {
//            //1、判断是否登录
//            orderSn = seckillService.kill(killId,key,num);
//            model.addAttribute("orderSn",orderSn);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        long s3 = System.currentTimeMillis();
//        log.info("耗时总啦啦啦啦啦啦..." + (s3 - s1));
//
//        return "success";
//    }

    /**
     * 处理秒杀请求 这里的任务只需要把秒杀请求放进秒杀等待队列中
     * @param killId
     * @param key
     * @param num
     * @param model
     * @return
     */
    @GetMapping(value = "/kill")
    @ResponseBody
    @SaCheckLogin
    public R seckill(@RequestParam("killId") String killId,
                          @RequestParam("key") String key,
                          @RequestParam("num") Integer num,
                          Model model) {
        SeckillTo seckillTo = new SeckillTo(killId, key, num);
        rabbitTemplate.convertAndSend("seckill-exchange", "wait.exec.seckill", seckillTo);
        return R.ok("秒杀请求成功发送到mq");
    }

    /**
     * 获取秒杀结果
     * @return
     */
    @GetMapping("/result/get")
    @ResponseBody
    @SaCheckLogin
    public R getSeckillResult(@RequestParam("killId") String killId, @RequestParam("key") String randomKey) {
        killId = killId.replace("_", "-");
        String key = "1-" + killId;
        Boolean seckillSuccess = redisTemplate.hasKey(key);
        if (seckillSuccess) {
            return R.ok("秒杀成功");
        } else {
            String s = redisTemplate.opsForValue().get("seckill:stock:" + randomKey);
            int i = Integer.parseInt(s);
            if (i == 0) {
                return R.ok("秒杀已结束");
            } else {
                return R.error("系统繁忙");
            }
        }
    }

}
